<?php

namespace App\Libs\Upload;

use App\Libs\Utils;

class Base
{
    /*
     * 上传文件file的类型，前台传过来的名称，如video、image
     */
    public $type;
    /**
     * 上传文件的大小
     * @var
     */
    public $size;
    public $clientMediaType;

    public function __construct($request, $type = null)
    {
        $this->request = $request;
        if (empty($type)) {
            $files = $this->request->getSwooleRequest()->files;
            $this->type = array_keys($files)[0];
        } else {
            $this->type = $type;
        }
    }

    public function upload()
    {
        if ($this->type != $this->fileType) {
            return false;
        }

        $resource = $this->request->getUploadedFile($this->type);
        $this->size = $resource->getSize();
        $this->checkSize();
        $fileName = $resource->getClientFileName();
//        print_r($fileName);

        $this->clientMediaType = $resource->getClientMediaType();
        $this->checkMediaType();
        $file = $this->getFile($fileName);
        $flag = $resource->moveTo($file);
        if (!empty($flag)) {
            return $this->file;
        }

        return false;
    }

    public function getFile($filename)
    {
        $info = pathinfo($filename);
        $extension = $info['extension'];
        $dirname = '/'.$this->type.'/'.date('Y').'/'.date('m');
        $dir = EASYSWOOLE_ROOT.'/webroot'.$dirname;
        @mkdir($dir, 0777, true);
        $basename = '/'.Utils::getFileKey($filename).'.'.$extension;
        $this->file = $dirname.$basename;
        return $dir.$basename;
    }

    /**
     * 检测文件拓展名是否合法
     * @throws \Exception
     */
    public function checkMediaType()
    {
        $clientMediaType = explode('/', $this->clientMediaType);
        $clientMediaType = $clientMediaType[1] ?? "";
        if (empty($clientMediaType)) {
            throw new \Exception("上传{$this->type}文件不合法");
        }
        if (!in_array($clientMediaType, $this->fileExtTypes)) {
            throw new \Exception("上传{$this->type}文件不合法");
        }
    }

    public function checkSize()
    {
        if (empty($this->size)) {
            return false;
        }


    }
}